package pl.uz.zgora.plan;


import java.io.IOException;
import java.text.ParseException;

import org.xmlpull.v1.XmlPullParserException;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class NextClassWidget extends AppWidgetProvider {
	
	private static RemoteViews views = new RemoteViews("pl.uz.zgora.plan", R.layout.widget_next_stretched);	
	private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
	private static final String ACTION_UPDATE_RECEIVER = "ActionUpdate";
	private static final String ACTION_APP_RECEIVER = "ActionApp";
	private static final String ACTION_SETTINGS_RECEIVER = "ActionSettings";
	private static boolean buttonStripeVisible = false;
	private static AppWidgetManager m_AppWidgetManager = null;
	
	public static void handleError(AppWidgetManager appWidgetManager, int appWidgetId, final RemoteViews views) {
		handleError(appWidgetManager, appWidgetId, "Błąd podczas pobierania danych", views);
	}
	
	public static void handleError(AppWidgetManager appWidgetManager, int appWidgetId, final String errorMsg, final RemoteViews views) {
		views.setViewVisibility(R.id.teacher, View.INVISIBLE);
		views.setTextViewText(R.id.className, errorMsg);
		views.setViewVisibility(R.id.startTime, View.INVISIBLE);
		views.setViewVisibility(R.id.subgroup, View.INVISIBLE);
		views.setViewVisibility(R.id.building, View.INVISIBLE);
		views.setViewVisibility(R.id.classNumber, View.INVISIBLE);
		appWidgetManager.updateAppWidget(appWidgetId, views);
	}
	  
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		m_AppWidgetManager = appWidgetManager;
		if(appWidgetIds == null) {
			Log.e("nextclassWidget", "ids is null");
		}
		if(appWidgetIds.length == 0) {
			Log.e("nextclassWidget", "ids is 0");
		}
		final int N = appWidgetIds.length;
		Log.d("nextclassWidget", "updating widget");
		for (int i=0; i<N; i++) {
			final Integer appWidgetId = appWidgetIds[i];
			
			refreshWidgetUI(context, appWidgetId);

			/*try {
				showNextClassOnWidget(context, appWidgetManager, appWidgetId);
				showCurrentClassOnWidget(context);
			} catch (ParseException e) {
				handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
			}	*/
            
            appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}
	
	private static void manageButtonActions(Context context) {
		// Obsługa kliknięcia widgetu
		Intent intent = new Intent(context, NextClassWidget.class);
        intent.setAction(ACTION_WIDGET_RECEIVER);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, 0);
        views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
        // Obsługa kliknięcia przycików widgetu
        intent.setAction(ACTION_APP_RECEIVER);
        pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, 0);
        views.setOnClickPendingIntent(R.id.widget_app, pendingIntent);
        
        intent.setAction(ACTION_UPDATE_RECEIVER);
        pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, 0);
        views.setOnClickPendingIntent(R.id.widget_update, pendingIntent);
        
        intent.setAction(ACTION_SETTINGS_RECEIVER);
        pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, 0);
        views.setOnClickPendingIntent(R.id.widget_settings, pendingIntent);
	}
	
	public static void refreshWidgetUI(Context context, int appWidgetId) {
		PrefrencesManager pm = PrefrencesManager.getInstance(context);
		Boolean doStretchWidget = pm.getBooleanFromPreferences("stretch_widget");
		if(doStretchWidget) {
			views = new RemoteViews("pl.uz.zgora.plan", R.layout.widget_next_stretched);
		} else {
			views = new RemoteViews("pl.uz.zgora.plan", R.layout.widget_next);
		}
		
		try {
			showCurrentClassOnWidget(context);
			showNextClassOnWidget(context, m_AppWidgetManager, appWidgetId);
		} catch (ParseException e) {
			handleError(m_AppWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
		}
		
		manageButtonActions(context);
		
		Integer color = pm.getIntFromPreferences("widget_bg_color");
		if(color != -1) {
			views.setInt(R.id.widget_layout, "setBackgroundColor", color);
		} else {
			views.setInt(R.id.widget_layout, "setBackgroundColor", Color.argb(180, 0, 0, 0));
		}
		
		if(m_AppWidgetManager != null) {
			m_AppWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}
	
	public static void showCurrentClassOnWidget(Context context) throws ParseException {
		PlanUzDataSource planDataSource = new PlanUzDataSource(context);
		Przedmiot przedmiot = planDataSource.getCurrentClass();
		if(przedmiot != null) {
			views.setTextViewText(R.id.widget_now_class, przedmiot.getNazwa() + " (" + przedmiot.getRodzajZajec() + ")");
			views.setTextViewText(R.id.widget_now_class_left, "Pozostało " + planDataSource.getCurrentClassLeft() + " min. " + "(" + przedmiot.getGodzinaZakonczenia() + ")");
			views.setViewVisibility(R.id.widget_now_class_left, View.VISIBLE);
			
		} else {
			views.setTextViewText(R.id.widget_now_class, "Brak zajęć");
			views.setViewVisibility(R.id.widget_now_class_left, View.INVISIBLE);
		}
	}
	
	public static void showNextClassOnWidget(Context context, AppWidgetManager appWidgetManager, Integer appWidgetId) throws ParseException {
		final PlanUzDataSource planDataSource = new PlanUzDataSource(context);
		Przedmiot przedmiot = null;
		try {
			przedmiot = planDataSource.getNextTodayClass();
		} catch (SQLException e) {
			handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
		} catch (IOException e) {
			handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
		} catch (XmlPullParserException e) {
			handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
		}

		if(przedmiot != null) {
			views.setTextViewText(R.id.widget_next_class_day, "Dzisiaj");
			// Godzina rozpoczęcia
			views.setTextViewText(R.id.startTime, przedmiot.getGodzinaRozpoczecia() + " - " + przedmiot.getGodzinaZakonczenia());
			views.setTextViewText(R.id.className, przedmiot.getNazwa() + " (" + przedmiot.getRodzajZajec() + ")");
			if(!przedmiot.getPodgrupa().trim().equals("")) {
				views.setTextViewText(R.id.subgroup, przedmiot.getPodgrupa());
				views.setViewVisibility(R.id.subgroup, View.VISIBLE);
			} else {
				views.setViewVisibility(R.id.subgroup, View.INVISIBLE);
			}
			views.setTextViewText(R.id.teacher, przedmiot.getNauczyciel(context).getNazwa());
			views.setTextViewText(R.id.classNumber, przedmiot.getSala(context).getNazwa());
			views.setTextViewText(R.id.building, przedmiot.getSala(context).getSymbolBudynku());

			views.setViewVisibility(R.id.classNumber, View.VISIBLE);
			views.setViewVisibility(R.id.building, View.VISIBLE);
			views.setViewVisibility(R.id.startTime, View.VISIBLE);
		} else {
			try {		
				przedmiot = planDataSource.getNextClassFromOtherDay();
			} catch (SQLException e) {
				handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
			} catch (IOException e) {
				handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
			} catch (XmlPullParserException e) {
				handleError(appWidgetManager, appWidgetId, e.getLocalizedMessage(), views);
			}

			if(przedmiot == null) {
				views.setTextViewText(R.id.className, "Brak innych zajęć w tygodniu");
				views.setViewVisibility(R.id.subgroup, View.INVISIBLE);
				views.setViewVisibility(R.id.classNumber, View.INVISIBLE);
				views.setViewVisibility(R.id.building, View.INVISIBLE);
				views.setViewVisibility(R.id.startTime, View.INVISIBLE);
			} else {
				views.setTextViewText(R.id.widget_next_class_day, przedmiot.getDzien() + " (" + przedmiot.getData().substring(0, 5) + ")");
				// Godzina rozpoczęcia
				views.setTextViewText(R.id.startTime, przedmiot.getGodzinaRozpoczecia() + " - " + przedmiot.getGodzinaZakonczenia());
				views.setTextViewText(R.id.className, przedmiot.getNazwa() + " (" + przedmiot.getRodzajZajec() + ")");
				if(!przedmiot.getPodgrupa().trim().equals("")) {
					views.setTextViewText(R.id.subgroup, przedmiot.getPodgrupa());
					views.setViewVisibility(R.id.subgroup, View.VISIBLE);
				} else {
					views.setViewVisibility(R.id.subgroup, View.INVISIBLE);
				}
				views.setTextViewText(R.id.teacher, przedmiot.getNauczyciel(context).getNazwa());
				views.setTextViewText(R.id.classNumber, przedmiot.getSala(context).getNazwa());
				views.setTextViewText(R.id.building, przedmiot.getSala(context).getSymbolBudynku());

				views.setViewVisibility(R.id.classNumber, View.VISIBLE);
				views.setViewVisibility(R.id.building, View.VISIBLE);
				views.setViewVisibility(R.id.startTime, View.VISIBLE);
			}
		}
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("onReceive()", "receiving widget");
	     if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { // Wywołanie przycisków
	    	 if(!buttonStripeVisible) {
	    		 views.setViewVisibility(R.id.widget_button_stripe, View.VISIBLE);
	    		 buttonStripeVisible = true;
	    	 } else {
	    		 views.setViewVisibility(R.id.widget_button_stripe, View.GONE);
	    		 buttonStripeVisible = false;
	    	 }
	    	 ComponentName cn = new ComponentName(context, NextClassWidget.class);
    		 AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
	     } else if(intent.getAction().equals(ACTION_APP_RECEIVER)) { // Aplikacja
	    	 
	    	 views.setViewVisibility(R.id.widget_button_stripe, View.GONE);
    		 buttonStripeVisible = false;
    		 
	    	 ComponentName cn = new ComponentName(context, NextClassWidget.class);
    		 AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
    		 
    		 Intent theActivity = new Intent(context, MainMenuActivity.class);
    		 theActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		 context.startActivity(theActivity);
    		 
	     } else if(intent.getAction().equals(ACTION_UPDATE_RECEIVER)) { // Odświeżenie
	    	 Log.d("WIDGET_UPDATE", "recieved on update click");
	    	 views.setViewVisibility(R.id.widget_button_stripe, View.GONE);
    		 buttonStripeVisible = false;
    		 
	    	 ComponentName cn = new ComponentName(context, NextClassWidget.class);
	    	 
	    	 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
	    	 appWidgetManager.updateAppWidget(cn, views);
    		 
    		 int[] appWidgetIds = appWidgetManager.getAppWidgetIds(cn);

    		 onUpdate(context, appWidgetManager, appWidgetIds);
    		 
    		 
	     } else if(intent.getAction().equals(ACTION_SETTINGS_RECEIVER)) { // Ustawienia
	    	 
	    	 views.setViewVisibility(R.id.widget_button_stripe, View.GONE);
    		 buttonStripeVisible = false;
    		 
	    	 ComponentName cn = new ComponentName(context, NextClassWidget.class);
    		 AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
    		 
    		 Intent theActivity = new Intent(context, WidgetSettingsActivity.class);
    		 theActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		 context.startActivity(theActivity);
	     }
	     super.onReceive(context, intent);
	}
}
